<!--
 * @Desc:
 * @author cheegon
 * @date 2024/07/01  上午10:41
-->
<template>
  <el-dialog :title="isEdit?'修改分类':'新增分类'" v-dialog-drag :visible.sync="isShowPop">
    <el-form style="text-align: left" ref="formRef" :model="formData"
             :rules="formRules" label-width="80px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="封面图片">
        <SimpleUpload :info="imageInfo" ref="uploadRef" @complete="handleUploadComplete"></SimpleUpload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialogMixin'
import SimpleUpload from '@/components/SimpleUpload.vue'
import { reqAddType, reqEditType } from '@/api/adminApi'

export default {
  name: "AEditTypeDialog",
  components: { SimpleUpload },
  props: [],
  mixins: [dialogMixin],
  data() {
    return {
      formData: {
        id:"",
        name: '',
        picUrl: ''
      },
      formRules: {
        name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
      },
      imageInfo: {
        fileType: 'img',
        limit: 1,
        imageList: []
      },
    }
  },
  created() {
  },
  methods: {
    refresh() {
      if (this.isEdit) {
        this.formData = { id:this.info.id,name: this.info.name, picUrl: this.info.picUrl }
        this.imageInfo.imageList = [this.info.picUrl]
        this.$nextTick(() => {
          this.$refs.uploadRef.refresh()
        })
      } else {
        this.formData = {}
      }
    },
    handleUploadComplete(value) {
      if (value && value.length) {
        this.formData.picUrl = value[0]
      } else {
        this.formData.picUrl = ''
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        if (!this.formData.picUrl) {
          this.$message.warning("请先上传图片")
          return
        }
        if (this.isEdit){
          reqEditType(this.formData).then(data => {
            this.$message.success("修改成功")
            this.isShowPop = false
            this.onComplete()
          })
        }else {
          reqAddType(this.formData).then(data => {
            this.$message.success("修改成功")
            this.isShowPop = false
            this.onComplete()
          })
        }
      })
    },
  }
}
</script>

<style lang="stylus" scoped>
.i_image {
  width 100px
  height 100px
}
</style>
